﻿using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Text;
using SourceCode.Workflow.Client;
using ASBCC.Database.Entity;
using ASBCC.Workflow.K2Manager;
using ASBCC.Database.Service;
using System.Data.Sql;
using System.Data;

namespace ASBCC.Workflow.K2Manager
{
    public class RejectActionHandler : ActionHandlerBase
    {
        #region Constructor

        public RejectActionHandler(SerializableDictionary dataFields, K2AppForm appForm, K2WorkItem workItem, K2ActionInfo actionInfo, string comment, K2AuditDestination auditDestination, List<K2User> outputDestinationUsers) :
            base(dataFields, appForm, workItem, actionInfo, comment, auditDestination, outputDestinationUsers)
        {
        }

        #endregion

        #region Override Methods
        /// <summary>
        /// 执行流程动作
        /// 重载该方法执行GotoActivity动作
        /// </summary>
        protected override void ExcuteAction()
        {
            GotoActivity(WorkItem.ProcInstId);
        }

        protected override void BuildProcessStamp()
        {
            base.BuildProcessStamp();
            //K2DataHelper.DisableProcessStamp(WorkItem.ProcInstId);
        }

        protected override void SendMail()
        {
            string actionType = GetActionType();
            string ApplicationNameEn = FlowProcess.ProcDisplayEn;
            string ApplicationNameCn = FlowProcess.ProcDisplayCn;

            Flow_ProcessMailConfigTableEntity mailConfig = K2DataHelper.GetProcessMailConfig(WorkItem.ProcName, WorkItem.ActivityName, actionType);
            if (mailConfig == null) return;

            EZVisitApplicationTableEntity entity = EZVisitApplicationManager.SelectByKeys(AppForm.FormId);
            if (entity == null) return;

            // 通知Applicant/Creator
            int toApplicantTemplate = mailConfig.ToApplicantTemplate ?? 0;
            if (toApplicantTemplate > 0)
            {
                EmployeeTableEntity applicantInfo = null;
                EmployeeTableEntity creatorInfo = null;

                if (AppForm.Applicant.UserId > 0 )
                {
                    applicantInfo = K2DataHelper.GetUserInfoById(AppForm.Applicant.UserId);
                }

                if (AppForm.Creator.UserId > 0 && AppForm.Creator.UserId != AppForm.Applicant.UserId)
                {
                    creatorInfo = K2DataHelper.GetUserInfoById(AppForm.Creator.UserId);
                }



               





                string auditUser = (AppForm.DelegateFrom.UserId <= 0 || AppForm.DelegateFrom.UserId == AppForm.CurrentUser.UserId) ?
                    AppForm.CurrentUser.UserEn : string.Format("{0}({1})", AppForm.CurrentUser.UserEn, AppForm.DelegateFrom.UserEn);

                if (CheckMailApplicantRule(applicantInfo))
                {

                    string[] appEmail = null;

                    DataSet ds = ProcedureManager.usp3_Select_RejectPersonByProcInstId(entity.ProcInstId);

                    if (ds.Tables[0].Rows.Count > 0)
                    {
                        DataTable dt = ds.Tables[0];

                        if (dt.Rows.Count > 0)
                            appEmail = new string[dt.Rows.Count];
                        else
                            appEmail = new string[1];

                        for (int i = 0; i < dt.Rows.Count; i++)
                        {
                            if (AppForm.CurrentUser.UserId.ToString() == dt.Rows[i]["OwnerID"].ToString())
                                continue;
                            string currentEmail = dt.Rows[i]["Email"] as string;

                            if (string.Compare(currentEmail, string.Empty, true) != 0)
                                appEmail[i] = currentEmail;
                        }

                    }
                    else
                    {
                        appEmail = new string[1];
                    }


                    string[] mailAddressArr = new string[] { applicantInfo.Email };
                    NameValueCollection collection = new NameValueCollection();
                    collection["{EnglishName}"] = applicantInfo.NameEN;
                    collection["{ChineseName}"] = applicantInfo.NameChinese;
                    if (!entity.EZVisitReqNoIsNull())
                        collection["{SerialNumber}"] = entity.EZVisitReqNo;
                    else
                        collection["{SerialNumber}"] = AppForm.ApplicationNo;

                    collection["{AuditUser}"] = auditUser;
                    collection["{AuditTime}"] = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");


                    collection["{FormURL}"] = DataFields[K2Consts.DataField_Key_FormURL].ToString();
                    collection["{Comments}"] = Comment;

                    NameValueCollection titleCollection = new NameValueCollection();
                    if (!entity.EZVisitReqNoIsNull())
                        titleCollection["{SerialNumber}"] = "EZVisit No：" + entity.EZVisitReqNo;
                    else
                        titleCollection["{SerialNumber}"] = AppForm.ApplicationNo;

                    MailService.MailSender(mailAddressArr, toApplicantTemplate, collection, titleCollection, appEmail);
                }

                if (CheckMailApplicantRule(creatorInfo))
                {
                   
                    string[] mailAddressArr = new string[] { creatorInfo.Email };
                    NameValueCollection collection = new NameValueCollection();
                    collection["{EnglishName}"] = creatorInfo.NameEN;
                    collection["{ChineseName}"] = creatorInfo.NameChinese;

                    if (!entity.EZVisitReqNoIsNull())
                        collection["{SerialNumber}"] = entity.EZVisitReqNo;
                    else
                        collection["{SerialNumber}"] = AppForm.ApplicationNo;
                    collection["{AuditUser}"] = auditUser;
                    collection["{AuditTime}"] = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
                    collection["{FormURL}"] = DataFields[K2Consts.DataField_Key_FormURL].ToString();
                    collection["{Comments}"] = Comment;

                    NameValueCollection titleCollection = new NameValueCollection();
                    if (!entity.EZVisitReqNoIsNull())
                        titleCollection["{SerialNumber}"] = "EZVisit No：" + entity.EZVisitReqNo;
                    else
                        titleCollection["{SerialNumber}"] = AppForm.ApplicationNo;

                    MailService.MailSender(mailAddressArr, toApplicantTemplate, collection, titleCollection);
                }
            }
        }

        protected override string GetActionType()
        {
            return K2ActionType.Reject;
        }

        #endregion
    }
}
